from django.shortcuts import render

from rest_framework.viewsets import GenericViewSet, ViewSet

from ending_framework_api.apps.order.models import Order
from ending_framework_api.apps.order.serializer import OrderSerializer
from registered.models import DetailedList

from utils.common_response import APIResponse
from rest_framework.response import Response

from libs.alipay_common import alipay

from utils.common_logging import logger


# Create your views here.
##############支付接口####################

class OrderView(GenericViewSet):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer

    def create(self, request, *args, **kwargs):
        ser = self.get_serializer(data=request.data, context={'request': request})
        ser.is_valid(raise_exception=True)
        ser.save()
        pay_url = ser.context.get('pay_url')
        return APIResponse(msg='下单成功', pay_url=pay_url)


class SuccessView(ViewSet):
    def get(self, request):
        try:
            out_trade_no = request.query_params.get('out_trade_no')
            Order.objects.get(out_trade_no=out_trade_no, order_status=1)
            print('成功')
            return APIResponse(msg='支付成功')
        except Exception as e:
            return APIResponse(code=101, msg='订单未支付')

    def post(self, request):
        print('post')
        try:
            # result_data = request.data.dict()  # 支付宝发送post请求给我们---》数据携带再请求体中---》urlencoded--》request.data不是字典格式，使用dict做成字典格式
            out_trade_no = request.query_params.get('out_trade_no')
            print(out_trade_no)
            # signature = result_data.pop('sign')
            # result = alipay.verify(result_data, signature)  # 验签通过表示是支付宝给的，不是别人伪造的
            # trade_status 确认订单付款成功了
            # if result and result_data['trade_status'] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
            # 完成订单修改：订单状态、流水号、支付时间
            Order.objects.filter(out_trade_no=out_trade_no).update(order_status=1,
                                                                   pay_time=request.query_params.get('timestamp'),
                                                                   trade_no=request.query_params.get('trade_no'))
            # 完成日志记录
            logger.warning('%s订单支付成功' % out_trade_no)
            return APIResponse()  # 必须这样，不能有别的东西
            # else:
            # logger.error('%s订单支付失败' % out_trade_no)
        except:
            logger.error('%s订单支付失败' % out_trade_no)
            return APIResponse(code=101,msg='订单支付失败')
